package cn.ac.iscas.action.paper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import cn.ac.iscas.bean.paper.*;
import cn.ac.iscas.service.paper.IConferencePaperService;
import cn.ac.iscas.service.paper.IJournalServive;


@Controller @Scope("prototype")
public class PaperExlIO{
	@Resource private IJournalServive journalPaperService;
	@Resource private IConferencePaperService conferencePaperService;
	JournalPaper journal = new JournalPaper();
	ConfererncePaper conference = new ConfererncePaper(); 	
	private File excel;
	private String excelContentType;
	private String excelFileName;
	private String uploadclass;
	 public File getExcel() {
		return excel;
	}
	public void setExcel(File excel) {
		this.excel = excel;
	}
	
	public String getExcelContentType() {
		return excelContentType;
	}
	public void setExcelContentType(String excelContentType) {
		this.excelContentType = excelContentType;
	}
	public String getExcelFileName() {
		return excelFileName;
	}
	public void setExcelFileName(String excelFileName) {
		this.excelFileName = excelFileName;
	}	
	public String getUploadclass() {
		return uploadclass;
	}
	public void setUploadclass(String uploadclass) {
		this.uploadclass = uploadclass;
	}

	/** *//** 总行数 */
    private int totalRows = 0;
    /** *//** 总列数 */
    private int totalCells = 0;
    /** *//** 构造方法 */
    public PaperExlIO()
    {    	
    }
    public String selectExcel()
    {
    	return "selectExcel";
    }
    /** *//**
    * 
    * 
    Description:[根据文件名读取excel文件]    
    * @param fileName
    * @return
    * @throws Exception
    */
    public String read()
	{	    
    	
    	String fileName = excelFileName;
    	System.out.print(fileName);
	    /** *//** 检查文件名是否为空或者是否是Excel格式的文件 */
	    if (fileName == null || !fileName.matches("^.+\\.(?i)((xls)|(xlsx))$"))
		    {
		    return "failed";
		    }
	    boolean isExcel2003 = true;
	    /** *//** 对文件的合法性进行验证 */
	    if (fileName.matches("^.+\\.(?i)(xlsx)$"))
	    {
	    	isExcel2003 = false;
	    }
	    File savefile = null;
	    String realpath = ServletActionContext.getServletContext().getRealPath("/excel");
	    
    	if(excel != null)
		{
			File savedir = new File(realpath);
			if(!savedir.exists()) savedir.mkdir();			
//			PaperDocument docInfo = new PaperDocument();		
			savefile = new File(savedir , excelFileName);
			try {
				FileUtils.copyFile(excel, savefile);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return "failed";
			}				
	  
		} 
    	System.out.print(savefile.getAbsolutePath());
	    try
	    {
	    /** *//** 调用本类提供的根据流读取的方法 */
	    	classify(new FileInputStream(savefile), isExcel2003);
	    }
	    catch (Exception ex)
	    {
	    	ex.printStackTrace();
	    	return "failed";
	    }
	    /** *//** 返回最后读取的结果 */
	    return "success";
	}
    /** *//**
    * 
    * 
    Description:[根据流读取Excel文件]
    * 
    Created by [Huyvanpull] [Jan 20, 2010]
    * 
    Midified by [modifier] [modified time]
    * 
    * 
    * @param inputStream
    * @param isExcel2003
    * @return
    */
    public void classify(InputStream inputStream,boolean isExcel2003)
    {
	    
	    try
	    {
		    /** *//** 根据版本选择创建Workbook的方式 */
		    Workbook wb = isExcel2003 ? new HSSFWorkbook(inputStream)
		    : new XSSFWorkbook(inputStream);
		    readWorkbook(wb);
		}
	    catch (IOException e)
	    {
	    	e.printStackTrace();
	    }
	    return;
	}
    /** *//**
    * 
    * 
    Description:[得到总行数] 
    * @return
    */
    public int getTotalRows()
    {
    return totalRows;
    }
    /** *//**
    * 
    * 
    Description:[得到总列数]
    * 
    * @return
    */
    public int getTotalCells()
    {
    return totalCells;
    }
    /** *//**
    * 
    * 
    Description:[读取数据]
    *   
    * @param wb
    * @return
    */
    @SuppressWarnings("unchecked")
	private void readWorkbook(Workbook wb)
	{	   
	    /** *//** 得到第一个sheet */
	    Sheet sheet = wb.getSheetAt(0);
	    this.totalRows = sheet.getPhysicalNumberOfRows();
	    if (this.totalRows >= 1 && sheet.getRow(0) != null)
	    {
	    	this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
	    }
	    /** *//** 循环Excel的行 */
	    //excel从第0行开始，鉴于第0行要存放条目，从第一行开始遍历
	    for (int r = 1; r < this.totalRows; r++)
	    {
	    	Row row = sheet.getRow(r);
	    	if (row == null)
	    	{
	    		continue;
	    	}
	    	ArrayList rowList = new ArrayList();
	    	/** *//** 循环Excel的列 */
	    	for (short c = 0; c < this.getTotalCells(); c++)
	    	{
	    		Cell cell = row.getCell(c);
	    		String cellValue = "";
	    		if (cell == null)
	    		{
	    			rowList.add(cellValue);
	    			continue;
	    		}
	    		/** *//** 处理数字型的,自动去零 */
	    		if (Cell.CELL_TYPE_NUMERIC == cell.getCellType())
	    		{
	    			/** *//** 在excel里,日期也是数字,在此要进行判断 */
	    			if (HSSFDateUtil.isCellDateFormatted(cell))
	    			{
	    				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	    				cellValue = dateFormat.format(cell.getDateCellValue()); 
	    			}
	    			else
	    			{
	    				cellValue = (int)cell.getNumericCellValue() + "";
	    			}
	    		}
	    		/** *//** 处理字符串型 */
	    		else if (Cell.CELL_TYPE_STRING == cell.getCellType())
	    		{
	    			cellValue = cell.getStringCellValue();
	    		}
	    		/** *//** 处理布尔型 */
	    		else if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType())
	    		{
	    			cellValue = cell.getBooleanCellValue() + "";
	    		}
	    		/** *//** 其它的,非以上几种数据类型 */
	    		else
	    		{
	    			cellValue = cell.toString() + "";
	    		}	    		
	    		rowList.add(cellValue);
	    	}
//	    	HttpServletRequest req = ServletActionContext.getRequest();
//	    	uploadclass = req.getParameter("uploadclass"); 
	    	System.out.println("uploadclass:"+uploadclass);
	    	if(uploadclass.equals("journal"))
	    	{
	    		addToJournal(rowList);
	    	}
	    	if(uploadclass.equals("conference"))
	    	{
	    		if(row == null){System.out.println("row不攒在111");}
	    		addToConference(rowList);
	    	}
	    	if(uploadclass.trim().equals(""))
	    	{
	    		System.out.println("uploadclass:是空的");
	    	}
	    }
	    return;
	}
   
	private void addToJournal(ArrayList rowList)
    {    	
    	journal.setPaperTittle((String)rowList.get(0));
    	journal.setFirstAuthor((String)rowList.get(1));
    	journal.setSecondAuthor((String)rowList.get(2));
    	journal.setThirdAuthor((String)rowList.get(3));
    	journal.setFourthAuthor((String)rowList.get(4));
    	journal.setFifthAuthor((String)rowList.get(5));
    	journal.setSixthAuthor((String)rowList.get(6));    	
    	if(!rowList.get(7).toString().equals(""))
    		journal.setStartPage(Integer.parseInt((String)rowList.get(7)));    	
    	if(!rowList.get(8).toString().equals(""))
    		journal.setEndPage(Integer.parseInt((String)rowList.get(8)));
    	journal.setEIInclude(((String)rowList.get(9)).trim().toUpperCase().equals("TRUE")?true:false);
    	journal.setSCiinlude(((String)rowList.get(10)).trim().toUpperCase().equals("TRUE")?true:false);
    	if(((String)rowList.get(11)).equals("已发表"))
    	{
    		journal.setState(State.已发表);
    	}
    	else if(((String)rowList.get(11)).equals("已投出"))
    	{
    		journal.setState(State.已投出);
    	} 
    	else if(((String)rowList.get(11)).equals("已录用"))
    	{
    		journal.setState(State.已录用);
    	} 
    	if(((String)rowList.get(12)).trim().equals("会议论文"))
    	{
    		journal.setPaperType(PaperType.会议论文);
    	}
    	else if(((String)rowList.get(12)).trim().equals("期刊论文"))
    	{
    		journal.setPaperType(PaperType.期刊论文);
    	}	
    	
    	journal.setKeyWord((String)rowList.get(13));
    	journal.setPaperAbstract((String)rowList.get(14));
    	journal.setReviewComments((String)rowList.get(15));
    	journal.setNote((String)rowList.get(16));
    	journal.setPublicationYear((String)rowList.get(17));
    	journal.setPublicationJournal((String)rowList.get(18));
    	if(((String)rowList.get(19)).equals("国际"))
    	{
    		journal.setJournalLevel(JournalLevel.国际);
    	}
    	else if(((String)rowList.get(19)).equals("核心"))
    	{
    		journal.setJournalLevel(JournalLevel.核心);
    	} 
    	else if(((String)rowList.get(19)).equals("一级"))
    	{
    		journal.setJournalLevel(JournalLevel.一级);
    	}
    	if(!rowList.get(20).toString().equals(""))
    		journal.setVolume(Integer.parseInt((String)rowList.get(20)));
    	if(!rowList.get(21).toString().equals(""))
    		journal.setIssue(Integer.parseInt((String)rowList.get(21)));
    	if(journalPaperService == null)
    	{
    		System.out.print("mmmmmmm");
    	}
    	journalPaperService.save(journal);
    }
	
	 private void addToConference(ArrayList rowList) {
		 	conference.setPaperTittle((String)rowList.get(0));
	    	conference.setFirstAuthor((String)rowList.get(1));
	    	conference.setSecondAuthor((String)rowList.get(2));
	    	conference.setThirdAuthor((String)rowList.get(3));
	    	conference.setFourthAuthor((String)rowList.get(4));
	    	conference.setFifthAuthor((String)rowList.get(5));
	    	conference.setSixthAuthor((String)rowList.get(6));    	
	    	if(!rowList.get(7).toString().equals(""))
	    		conference.setStartPage(Integer.parseInt((String)rowList.get(7)));    	
	    	if(!rowList.get(8).toString().equals(""))
	    		conference.setEndPage(Integer.parseInt((String)rowList.get(8)));
	    	conference.setEIInclude(((String)rowList.get(9)).trim().toUpperCase().equals("TRUE")?true:false);
	    	conference.setSCiinlude(((String)rowList.get(10)).trim().toUpperCase().equals("TRUE")?true:false);
	    	if(((String)rowList.get(11)).equals("已发表"))
	    	{
	    		conference.setState(State.已发表);
	    	}
	    	else if(((String)rowList.get(11)).equals("已投出"))
	    	{
	    		conference.setState(State.已投出);
	    	} 
	    	else if(((String)rowList.get(11)).equals("已录用"))
	    	{
	    		conference.setState(State.已录用);
	    	} 
	    	if(((String)rowList.get(12)).trim().equals("会议论文"))
	    	{
	    		conference.setPaperType(PaperType.会议论文);
	    	}
	    	else if(((String)rowList.get(12)).trim().equals("期刊论文"))
	    	{
	    		conference.setPaperType(PaperType.期刊论文);
	    	}	
	    	
	    	conference.setKeyWord((String)rowList.get(13));
	    	conference.setPaperAbstract((String)rowList.get(14));
	    	conference.setReviewComments((String)rowList.get(15));
	    	conference.setNote((String)rowList.get(16));
	    	conference.setPublicationYear((String)rowList.get(17));
	    	conference.setConferenceName((String)rowList.get(18));
	    	if(((String)rowList.get(19)).equals("国际"))
	    	{
	    		conference.setConferenceType(ConferenceType.国际);
	    	}
	    	else if(((String)rowList.get(19)).equals("国内"))
	    	{
	    		conference.setConferenceType(ConferenceType.国内);
	    	} 
	    	if(!rowList.get(20).toString().equals(""))
	    	{
		    	Calendar startTime = Calendar.getInstance();
		    	StringTokenizer st = new StringTokenizer((String)rowList.get(20),"-");
		    	int year = Integer.parseInt(st.nextToken());
		    	int month = Integer.parseInt(st.nextToken());
		    	int date = Integer.parseInt(st.nextToken());
		    	startTime.set(year, month, date);		    	
		    	conference.setConferenceStartTime(startTime);
	    	}
	    	if(!rowList.get(21).toString().equals(""))
	    	{
		    	Calendar endTime = Calendar.getInstance();
		    	StringTokenizer st = new StringTokenizer((String)rowList.get(21),"-");
		    	int year = Integer.parseInt(st.nextToken());
		    	int month = Integer.parseInt(st.nextToken());
		    	int date = Integer.parseInt(st.nextToken());
		    	endTime.set(year, month, date);		    
		    	conference.setConferenceEndTime(endTime);
	    	}

	    	conference.setConferenceAddress((String)rowList.get(22));
	    	conference.setConferenceShortName((String)rowList.get(23));
	    	conference.setRecommendJournal((String)rowList.get(24));
	    	
	    	
	    	conferencePaperService.save(conference);	
	    	System.out.println("----脱管对象id----"+conference.getId());
			
		}
    /** *//**
    * 
    * 
    Description:[正确地处理整数后自动加零的情况]
  
    * @param sNum
    * @return
    */
    private String getRightStr(String sNum)
	{
	    DecimalFormat decimalFormat = new DecimalFormat("#.000000");
	    String resultStr = decimalFormat.format(new Double(sNum));
	    if (resultStr.matches("^[-+]?\\d+\\.[0]+$"))
	    {
	    resultStr = resultStr.substring(0, resultStr.indexOf("."));
	    }
	    return resultStr;
	}   

	public IJournalServive getJournalPaperService() {
		return journalPaperService;
	}
	public void setJournalPaperService(IJournalServive journalPaperService) {
		this.journalPaperService = journalPaperService;
	}
	public IConferencePaperService getConferencePaperService() {
		return conferencePaperService;
	}
	public void setConferencePaperService(
			IConferencePaperService conferencePaperService) {
		this.conferencePaperService = conferencePaperService;
	}
	public JournalPaper getJournal() {
		return journal;
	}
	public void setJournal(JournalPaper journal) {
		this.journal = journal;
	}
	public ConfererncePaper getConferencePaper() {
		return conference;
	}
	public void setConferencePaper(ConfererncePaper conferencePaper) {
		this.conference = conferencePaper;
	}
	

}
